简体   繁体   English

按值获取数组索引

[英]Get array index by value

I'm trying to get array index by value. 我试图按值获取数组索引。

I have this code: 我有以下代码:

var squares = new Array();
for (var i = 1; i <= 160; i++) {
    squares.push(i);
}

angular.element('.click').click(function () {
    var squareId = angular.element(this).attr('id');
    var fisk = squares.indexOf(squareId);
    console.log(fisk);
});

This only returns -1, thus, It can't be found. 这仅返回-1,因此找不到它。 If a replace squareId with a number in indeOf, it works perfect, but if I use a variable, It don't work. 如果用indeOf中的数字替换squareId,则效果很好,但是如果使用变量,则不起作用。

Anyone who can help me? 谁能帮助我?

You are initializing your array values with numbers between 1 and 160, so squares.indexOf(1) for example would return 0. 您正在使用1到160之间的数字初始化数组值,因此例如squares.indexOf(1)将返回0。

What you want to do is initialize the array with the actual ids of your elements. 您要做的是使用元素的实际ID初始化数组。

See Example Fiddle 参见小提琴示例

It's because the variable squareId could be returning a string value. 这是因为变量squareId可能返回字符串值。 The function indexOf can't find the string because it has numbers in the array. 函数indexOf找不到字符串,因为它在数组中有数字。

// string search
var squareId = '2';
var fisk = squares.indexOf(squareId);
console.log('This will not be found ' + fisk);

// number search
var squareId = Number('2');
var fisk = squares.indexOf(squareId);
console.log('This will be found ' + fisk);

See similar question 看到类似的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM