javascript js数组中的字符串索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10326635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:29:20  来源:igfitidea点击:

String index in js array

javascriptarraysindexing

提问by palAlaa

I want to put specific string in addition to a number to the index of array,

除了数字之外,我还想将特定的字符串放入数组的索引中,

I make like this

我是这样的

 var array= new Array();
 $(document).ready(function(){
  array= addToArray();
  console.log( "array size " + array.length);
 });

function addToArray(){
    var i = 0;
    var tmpArray = new Array();
    while(i<10){
       if(i>9){
          addToArray();
          i++;
    }
    else{
        tmpArray ["elem"+i] = "i";
        console.log(tmpArray ["elem"+i]); //it prints out !!!
        i++;
    }
 }
 console.debug(tmpArray );

  return tmpArray ;

}

? when I print out the tmpArray it's empty also the size is 0, when I remove the "elem" from index of array it works properly, what should I do? here's a real example http://jsfiddle.net/dfg3x/

? 当我打印出 tmpArray 时,它是空的,大小也为 0,当我从数组的索引中删除“elem”时,它可以正常工作,我该怎么办?这是一个真实的例子http://jsfiddle.net/dfg3x/

回答by Michael Berkowski

JavaScript doesn't have string array keys like PHP & some other languages. What you have done is to add a property named elem + ito the tmpArrayobject. It doesn't affect the array's .lengthproperty, even though the property is there and accessible, and it is notaccessible via array methods like .pop(), .shift()

JavaScript 没有像 PHP 和其他一些语言那样的字符串数组键。您所做的是为对象添加一个命名elem + itmpArray属性。它不会影响该阵列的.length性能,即使财产是存在的,可访问的,这是不是通过阵列的方法,如访问.pop(), .shift()

Perhaps instead you should declare tmpArrayas an object literal since you don't appear to be using it with any numeric keys.

也许您应该将其声明tmpArray为对象文字,因为您似乎没有将它与任何数字键一起使用。

function addToArray() {
    var i = 0;
    // Make an object literal
    var tmpObj = {};
    while(i<10) {
       if(i>9) {
          addToArray();
          i++;
       }
       else {
          tmpObj["elem"+i] = "i";
          console.log(tmpObj["elem"+i]); //it prints out !!!
          i++;
       }
    }
    console.debug(tmpObj );

    return tmpObj ;
}