初始化JavaScript数组 [英] Initializing a javascript array

查看:104
本文介绍了初始化JavaScript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有另一种(更漂亮)的方式来初始化这个JavaScript数组?

  VAR计数器= [];
    计数器[A] = 0;
    计数器[B] = 0;
    计数器[C] = 0;
    计数器[D] = 0;
    计数器[E] = 0;
    计数器[F] = 0;
    计数器[G] =​​ 0;


解决方案

一个。那也不行,或者至少不是办法,你会希望它。您初始化什么时候你最有可能寻找的是一个散列的数组。 计数仍然会返回 [] 0 除非你改变的第一行计数器= {}; 。该属性将存在,​​但它是一个令人困惑的使用 [] 来存储键 - 值对。

A:

  VAR计数器= {A:0,B:0 C:0 D:0 E:0,F:0,G:0};

Is there another (more beautiful) way to initialize this Javascript array?

    var counter = [];
    counter["A"] = 0; 
    counter["B"] = 0;
    counter["C"] = 0;
    counter["D"] = 0;
    counter["E"] = 0;
    counter["F"] = 0;
    counter["G"] = 0;

解决方案

A. That doesn't work, or at least not the way you'd hope it to. You initialized an array when what you're most likely looking for is a hash. counter will still return [] and have a length of 0 unless you change the first line to counter = {};. The properties will exist, but it's a confusing use of [] to store key-value pairs.

B:

var counter = {A: 0, B: 0, C: 0, D: 0, E: 0, F: 0, G: 0};

这篇关于初始化JavaScript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆