我在获取索引时遇到问题,如果在数组中有一些相似的单词,但索引位置不同,当我选择其中一个单词时,我得到的索引不是来自单词,而是从中选择相同的单词在以前的位置
例如,我有一句话:
收获是收集的过程
粗体字是我选择的单词..
这是我的代码:
var str = "The Harvest is the process of gathering";
var myArray = str.split ("");
var Select = "the";
Run Code Online (Sandbox Code Playgroud)
我有这样的功能:
function getIndex (arrayItem, item) {
for (var x = 0; x <arrayItem.length; x + +) {
if (arrayItem [x] == item) {
return x;
}
}
return -1;
}
var idx = getIndex (myArray, Select);
Run Code Online (Sandbox Code Playgroud)
如何获得该指数?
您可能希望完全避免这种情况并使用String对象的indexOf方法:
var str = "The Harvest is the process of gathering";
var idx = str.indexOf('the');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7624 次 |
| 最近记录: |