获取新添加元素的数组索引

3
我把一个新条目推入数组后,进行排序,想获取它的索引。

http://jsfiddle.net/dPwQA/2/

function sortInt(a, b) {
    return a - b;
}
numbers = [7,6];
numbers.sort(sortInt);
$('#text').text(numbers.toString());

$('button').click(function () {
    numbers.push('4');
    alert(numbers.indexOf("6")); // doesn't work
    numbers.sort(sortInt);
    $('#text').text(numbers.toString());
});

4
你是否故意在数组中混合字符串和数字?你没有"6",只有6。 - Denys Séguret
1
你有一个数值,现在想要找到对应的字符串数值。 - Arun P Johny
可能是get indexOf newly pushed item的重复问题。 - LeGEC
2个回答

0

使用这个

alert(numbers.indexOf(6));

同时,在按下4的时候,你应该这样做

numbers.push(4)

替代

numbers.push('4')

因为 '4' 将 4 视为字符串而不是数字。

希望这可以帮到你...


0

移除 6 周围的引号。

应该是:

alert(numbers.indexOf(6));

用这个替代:

alert(numbers.indexOf("6"));

编辑:

当我说要去掉围绕着6的引号时,我应该是指在任何地方都要去掉。

应该变成这样:

numbers.push(4);

与之相反:

numbers.push('4');


哦,现在我想检查新输入的数组项,它似乎在这里不起作用http://jsfiddle.net/dPwQA/4/。 - Bernardo Baalen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接