如何比較來自HTML的字符串與數組並獲取其位置?如何將字符串與JavaScript上的數組內容進行比較?
var fruit = ["apple", "banana"];
var $textOfHtml = "apple";
的問題是如何得到這樣的事情如下:
"apple" is on the [0] position?
謝謝你們。
如何比較來自HTML的字符串與數組並獲取其位置?如何將字符串與JavaScript上的數組內容進行比較?
var fruit = ["apple", "banana"];
var $textOfHtml = "apple";
的問題是如何得到這樣的事情如下:
"apple" is on the [0] position?
謝謝你們。
你必須使用陣列的indexOf()方法來找到你所需的值
<body>
<script>
var array = ["apple","banana"];
var text = "banana";
var position = array.indexOf(text);
alert(position);
</script>
</body>
的當前位置作爲意見建議,要使用indexOf。
使用你的代碼,這裏是用法:
var fruit = ["apple","banana"]
var $textOfHtml = "apple"
var i = fruit.indexOf($textOfHtml)
var str = $textOfHtml + ' is on the [' + i + '] position'
的的indexOf()方法搜索指定項目的陣列,並返回其位置。
var Index = fruit .indexOf($textOfHtml);
alert($textOfHtml+" is on the ["+Index +"] position");
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array,特別https://developer.mozilla.org/en-US/docs/ Web/JavaScript/Reference/Global_Objects/Array/findIndex和https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf –
使用['indexOf'](https:/ /developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)或循環。 – 4castle