gpt4 book ai didi

javascript - 如何在javascript中获取数组的索引

转载 作者:行者123 更新时间:2023-11-30 09:07:21 25 4
gpt4 key购买 nike

我在获取索引时遇到问题,如果数组中有一些相似的词但索引位置不同,当我选择其中一个词时,我得到的索引不是来自词而是我从中选择的前一个位置的同一个词

比如我有一句话:

收获是收集的过程

粗体字是我选择的字..

这是我的代码:

var str = "The Harvest is the process of gathering";
var myArray = str.split ("");
var Select = "the";

我有一个这样的函数:

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);

如何获取该索引?

最佳答案

您可能想完全避免这种情况并使用 String 对象的 indexOf 方法:

var str = "The Harvest is the process of gathering";
var idx = str.indexOf('the');

关于javascript - 如何在javascript中获取数组的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4093821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com