【问题标题】:What is the javascript equivalent of the PHP auto-assigning array feature?PHP 自动分配数组功能的 javascript 等价物是什么?
【发布时间】:2011-04-13 15:03:53
【问题描述】:

我正在尝试自动更新 javascript 数组,而不为键指定数字或字符串。该值应该只占用数组中的下一个数字键。

在 php 中你可以这样做:

<? 
myarray = array();
myarray[] = '1';
myarray[] = '2';
myarray[] = '3';

//this is equivalent to myarray[1] = '1', myarray[2] = '2', myarray[3] = '3'; 


?>

如何在 javascript 中做到这一点?

这会引发错误

$(function(){

var optionset = [];        

optionset[] = 'a';
optionset[] = 'b';

}); 

【问题讨论】:

    标签: php javascript arrays


    【解决方案1】:
     optionset.push('a');
     optionset.push('b');
    

    更多详情请见push() on W3Schools

    【讨论】:

      【解决方案2】:
      optionset.push('a', 'b');
      

      https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push

      通过附加给定元素并返回数组的新长度来改变数组。

      【讨论】:

        猜你喜欢
        • 2022-01-23
        • 2017-12-22
        • 2011-04-23
        • 1970-01-01
        • 1970-01-01
        • 2015-05-14
        • 2019-01-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多