Javascript 如何从数组集合返回索引-1
如何从数组集合返回索引-1 例:Javascript 如何从数组集合返回索引-1,javascript,array-map,Javascript,Array Map,如何从数组集合返回索引-1 例: 您可以通过indexOf函数执行此操作,请参见下文 function demo(id) { const ids= [1, 2, 3,4,5] ; var index = ids.indexOf(id); var res = i - 1; return res; } 要获取数组中元素的当前索引,请使用indexOf()array方法。当试图查找的元素在数组中不存在时,此方法返回-1 let index=null; 功能演示(id){ 常量id=
您可以通过indexOf函数执行此操作,请参见下文
function demo(id) {
const ids= [1, 2, 3,4,5] ;
var index = ids.indexOf(id);
var res = i - 1;
return res;
}
要获取数组中元素的当前索引,请使用
indexOf()
array方法。当试图查找的元素在数组中不存在时,此方法返回-1
let index=null;
功能演示(id){
常量id=[1,2,3,4,5];
//如何读取当前索引并返回索引-1。
索引=id.indexOf(id);
返回-1;
}
日志(演示(1),索引);
日志(演示(2),索引);
日志(演示(3),索引);
日志(演示(4),索引);
日志(演示(5),索引);
console.log(演示(6),索引);//-1,因为6不在数组中
console.log(演示(0),索引);//-1因为0不在数组中
如果要获取每个数组元素的当前索引-1,此方法将执行此操作
function checkId(id){
const ids= [1, 2, 3,4,5] ;
// return -1 if element doesn't exist
let Indx = ids.indexOf(id) == -1 ? -1 : ids.indexOf(id) -1;
//do this if you want the array element
//let arrEl = ids.indexOf(id) == -1 ? -1 : ids[ids.indexOf(id) -1];
return Indx;
}
console.log(checkId(3)) // returns 1
console.log(checkId(6)) // returns -1
我想这就是你要找的,但通过indexOf它怎么能返回index-1值;收益指数-1代码>仅供参考:JavaScript区分大小写。它是
函数
和常量
,而不是函数
和常量
。但是值可以是数组中的任何东西。它应该是一个映射函数吗?我可以是它每次都返回3的任何东西。所以我想在这里实现的是读取当前索引值并在这里返回索引-1。@TanmoySarkar要返回-1,只需编写return-1
,但这似乎没有意义。如果你只想返回-1,为什么还要费心去寻找索引呢?因为我将在redux中获得任何一个值,我必须传递上一个值以获得正确的id。@TanmoySarkar请查看更新的答案,它会满足你的要求。@TanmoySarkar在我的示例中,我将传入的id
的实际索引存储在index
变量中,因此,您可以在函数完成后使用该值,它将存储该函数上次检查的元素的索引。
function checkId(id){
const ids= [1, 2, 3,4,5] ;
// return -1 if element doesn't exist
let Indx = ids.indexOf(id) == -1 ? -1 : ids.indexOf(id) -1;
//do this if you want the array element
//let arrEl = ids.indexOf(id) == -1 ? -1 : ids[ids.indexOf(id) -1];
return Indx;
}
console.log(checkId(3)) // returns 1
console.log(checkId(6)) // returns -1