获取新推送元素的数组索引

get array index of newly pushed element

本文关键字:数组 索引 元素 新推送 获取      更新时间:2023-09-26

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

使用这个

alert(numbers.indexOf(6));

同样在推 4 时,您应该这样做

numbers.push(4)

而不是

numbers.push('4')

因为"4"将 4 作为字符串而不是数字。

希望这有帮助...

删除6 两边的引号。

它应该是:

alert(numbers.indexOf(6));

而不是:

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

编辑:

当我的意思是删除6周围的引号时,我应该说到处删除。

这应该变成:

numbers.push(4);

与以下相反:

numbers.push('4');