如何在Javascript中获取数组键?

时间:2021-08-23 07:37:38

I have an array created with this code:

我用这个代码创建了一个数组:

var widthRange = new Array();
widthRange[46] = { min:0,  max:52 };
widthRange[66] = { min:52, max:70 };
widthRange[90] = { min:70, max:94 };

I want to get each of the values 46, 66, 90 in a loop. I tried for (var key in widthRange) but this gives me a whole bunch of extra properties (I assume they are functions on the object). I can't use a regular for loop since the values are not sequential.

我想在循环中得到每个值46 66 90。我尝试过(在widthRange中使用var键),但是这给了我一大堆额外的属性(我假设它们是对象上的函数)。我不能使用常规的for循环,因为这些值不是顺序的。

11 个解决方案

#1


87  

You need to call the hasOwnProperty function to check whether the property is actually defined on the object itself (as opposed to its prototype), like this:

您需要调用hasOwnProperty函数来检查该属性是否在对象本身上定义(相对于它的原型),如下所示:

for (var key in widthRange) {
    if (key === 'length' || !widthRange.hasOwnProperty(key)) continue;
    var value = widthRange[key];
}

Note that you need a separate check for length.
However, you shouldn't be using an array here at all; you should use a regular object. All Javascript objects function as associative arrays.

注意,您需要单独检查长度。但是,这里根本不应该使用数组;您应该使用常规对象。所有Javascript对象都充当关联数组。

For example:

例如:

var widthRange = { };  //Or new Object()
widthRange[46] = { sel:46, min:0,  max:52 };
widthRange[66] = { sel:66, min:52, max:70 };
widthRange[90] = { sel:90, min:70, max:94 };

#2


59  

The stringified keys can be queried with Object.keys(array).

可以使用Object.keys(数组)查询经过字符串化的键。

#3


18  

If you are doing any kind of array/collection manipulation or inspection I highly recommend using Underscore.js. It's small, well-tested and will save you days/weeks/years of javascript headache. Here is its keys function:

如果您正在进行任何类型的数组/集合操作或检查,我强烈推荐使用Underscore.js。它很小,经过了良好的测试,将为您节省数天/数周/数年的javascript头痛。这是它的键功能:

Keys

Retrieve all the names of the object's properties.

检索对象属性的所有名称。

_.keys({one : 1, two : 2, three : 3});
=> ["one", "two", "three"]

#4


3  

for (var i = 0; i < widthRange.length; ++i) {
  if (widthRange[i] != null) {
    // do something
  }
}

You can't really get just the keys you've set because that's not how an Array works. Once you set element 46, you also have 0 through 45 set too (though they're null).

你不能只得到你设置的键因为数组不是这样工作的。一旦你设置了元素46,你也有了0到45的集合(尽管它们是空的)。

You could always have two arrays:

你总是可以有两个数组:

var widthRange = [], widths = [], newVal = function(n) {
  widths.push(n);
  return n;
};
widthRange[newVal(26)] = { whatever: "hello there" };

for (var i = 0; i < widths.length; ++i) {
  doSomething(widthRange[widths[i]]);
}

edit well it may be that I'm all wet here ...

编辑好吧,也许我全身都湿透了……

#5


2  

Say your array looked like arr = [ { a: 1, b: 2, c: 3 }, { a: 4, b: 5, c: 6 }, { a: 7, b: 8, c: 9 } ] (or possibly other keys) you could do

假设您的数组看起来像[{a: 1, b: 2, c: 3}, {a: 4, b: 5, c: 6}, {a: 7, b: 8, c: 9}](或者可能是其他的键)

arr.map((o) => {
    return Object.keys(o)
}).reduce((prev, curr) => {
    return prev.concat(curr)
}).filter((col, i, array) => {
    return array.indexOf(col) === i
});

["a", "b", "c"]

(“a”、“b”、“c”)

#6


2  

widthRange.map(function(_, i) { return i });

or

widthRange.map((_, i) => i);

#7


1  

Your original example works just fine for me:

你最初的例子很适合我:

<html>
<head>
</head>
<body>
<script>
var widthRange = new Array();
widthRange[46] = { sel:46, min:0,  max:52 };
widthRange[66] = { sel:66, min:52, max:70 };
widthRange[90] = { sel:90, min:70, max:94 };

var i = 1;
for (var key in widthRange)
{
    document.write("Key #" + i + " = " + key + "; &nbsp;&nbsp;&nbsp; min/max = " + widthRange[key].min + "/" + widthRange[key].max + "<br />");
    i++;
}
</script>
</html>

Results in the browser (Firefox 3.6.2 on Windows XP):

结果在浏览器(Firefox 3.6.2在Windows XP上):

Key #1 = 46;     min/max = 0/52
Key #2 = 66;     min/max = 52/70
Key #3 = 90;     min/max = 70/94

#8


1  

I think you should use an Object ({}) and not an array ([]) for this.

我认为您应该为此使用对象({})而不是数组([])。

A set of data is associated with each key. It screams for using an object. Do:

一组数据与每个键相关联。它使用对象时会发出尖叫声。做的事:

var obj = {};
obj[46] = { sel:46, min:0,  max:52 };
obj[666] = { whatever:true };

// This is what for..in is for
for (var prop in obj) {
  console.log(obj[prop]);
}

Maybe some utility stuff like this can help:

也许像这样一些实用的东西能帮上忙:

window.WidthRange = (function () {
  var obj = {};
  return {
    getObj: function () {return obj;}
    , add: function (key, data) {
        obj[key] = data;
        return this; // enabling chaining
      }
  }
})();

// Usage (using chaining calls):
WidthRange.add(66, {foo: true})
.add(67, {bar: false})
.add(69, {baz: 'maybe', bork:'absolutely'});

var obj = WidthRange.getObj();
for (var prop in obj) {
  console.log(obj[prop]);
}

#9


0  

Seems to work.

似乎工作。

var widthRange = new Array();
widthRange[46] = { sel:46, min:0,  max:52 };
widthRange[66] = { sel:66, min:52, max:70 };
widthRange[90] = { sel:90, min:70, max:94 };

for (var key in widthRange)
{
    document.write(widthRange[key].sel + "<br />");
    document.write(widthRange[key].min + "<br />");
    document.write(widthRange[key].max + "<br />");
}

#10


0  

I wrote a function what works fine with every instance of Objects (Arrays are those).

我编写了一个函数,它对每个对象实例(数组就是这些对象)都适用。

Object.prototype.toArray = function()
{
    if(!this)
    {
      return null;
    }

    var c = [];

    for (var key in this) 
    {
        if ( ( this instanceof Array && this.constructor === Array && key === 'length' ) || !this.hasOwnProperty(key) ) 
        {
            continue;
        }

        c.push(this[key]);
    }

    return c;
};

Usage:

用法:

var a   = [ 1, 2, 3 ];
a[11]   = 4;
a["js"] = 5;

console.log(a.toArray());

var b = { one: 1, two: 2, three: 3, f: function() { return 4; }, five: 5 };
b[7] = 7;

console.log(b.toArray());

Output:

输出:

> [ 1, 2, 3, 4, 5 ]
> [ 7, 1, 2, 3, function () { return 4; }, 5 ]

It may be useful for anyone.

它可能对任何人都有用。

#11


0  

... ????

…? ? ? ?

Alternatively, if you have a list of items you want to use...

或者,如果你有一个你想要使用的项目列表……

var range = [46, 66, 90]
    , widthRange=[]
    , write=[];

    widthRange[46] = { min:0, max:52 }; 
    widthRange[66] = { min:52, max:70 }; 
    widthRange[90] = { min:70, max:94 }; 

for(var x=0; x<range.length; x++){var key, wr;

    key = range[x];

    wr = widthRange[key] || false;

    if(wr===false){continue;}

    write.push(['key: #',key, ', min: ', wr.min, 'max:', wr.max].join(''));

    }

#1


87  

You need to call the hasOwnProperty function to check whether the property is actually defined on the object itself (as opposed to its prototype), like this:

您需要调用hasOwnProperty函数来检查该属性是否在对象本身上定义(相对于它的原型),如下所示:

for (var key in widthRange) {
    if (key === 'length' || !widthRange.hasOwnProperty(key)) continue;
    var value = widthRange[key];
}

Note that you need a separate check for length.
However, you shouldn't be using an array here at all; you should use a regular object. All Javascript objects function as associative arrays.

注意,您需要单独检查长度。但是,这里根本不应该使用数组;您应该使用常规对象。所有Javascript对象都充当关联数组。

For example:

例如:

var widthRange = { };  //Or new Object()
widthRange[46] = { sel:46, min:0,  max:52 };
widthRange[66] = { sel:66, min:52, max:70 };
widthRange[90] = { sel:90, min:70, max:94 };

#2


59  

The stringified keys can be queried with Object.keys(array).

可以使用Object.keys(数组)查询经过字符串化的键。

#3


18  

If you are doing any kind of array/collection manipulation or inspection I highly recommend using Underscore.js. It's small, well-tested and will save you days/weeks/years of javascript headache. Here is its keys function:

如果您正在进行任何类型的数组/集合操作或检查,我强烈推荐使用Underscore.js。它很小,经过了良好的测试,将为您节省数天/数周/数年的javascript头痛。这是它的键功能:

Keys

Retrieve all the names of the object's properties.

检索对象属性的所有名称。

_.keys({one : 1, two : 2, three : 3});
=> ["one", "two", "three"]

#4


3  

for (var i = 0; i < widthRange.length; ++i) {
  if (widthRange[i] != null) {
    // do something
  }
}

You can't really get just the keys you've set because that's not how an Array works. Once you set element 46, you also have 0 through 45 set too (though they're null).

你不能只得到你设置的键因为数组不是这样工作的。一旦你设置了元素46,你也有了0到45的集合(尽管它们是空的)。

You could always have two arrays:

你总是可以有两个数组:

var widthRange = [], widths = [], newVal = function(n) {
  widths.push(n);
  return n;
};
widthRange[newVal(26)] = { whatever: "hello there" };

for (var i = 0; i < widths.length; ++i) {
  doSomething(widthRange[widths[i]]);
}

edit well it may be that I'm all wet here ...

编辑好吧,也许我全身都湿透了……

#5


2  

Say your array looked like arr = [ { a: 1, b: 2, c: 3 }, { a: 4, b: 5, c: 6 }, { a: 7, b: 8, c: 9 } ] (or possibly other keys) you could do

假设您的数组看起来像[{a: 1, b: 2, c: 3}, {a: 4, b: 5, c: 6}, {a: 7, b: 8, c: 9}](或者可能是其他的键)

arr.map((o) => {
    return Object.keys(o)
}).reduce((prev, curr) => {
    return prev.concat(curr)
}).filter((col, i, array) => {
    return array.indexOf(col) === i
});

["a", "b", "c"]

(“a”、“b”、“c”)

#6


2  

widthRange.map(function(_, i) { return i });

or

widthRange.map((_, i) => i);

#7


1  

Your original example works just fine for me:

你最初的例子很适合我:

<html>
<head>
</head>
<body>
<script>
var widthRange = new Array();
widthRange[46] = { sel:46, min:0,  max:52 };
widthRange[66] = { sel:66, min:52, max:70 };
widthRange[90] = { sel:90, min:70, max:94 };

var i = 1;
for (var key in widthRange)
{
    document.write("Key #" + i + " = " + key + "; &nbsp;&nbsp;&nbsp; min/max = " + widthRange[key].min + "/" + widthRange[key].max + "<br />");
    i++;
}
</script>
</html>

Results in the browser (Firefox 3.6.2 on Windows XP):

结果在浏览器(Firefox 3.6.2在Windows XP上):

Key #1 = 46;     min/max = 0/52
Key #2 = 66;     min/max = 52/70
Key #3 = 90;     min/max = 70/94

#8


1  

I think you should use an Object ({}) and not an array ([]) for this.

我认为您应该为此使用对象({})而不是数组([])。

A set of data is associated with each key. It screams for using an object. Do:

一组数据与每个键相关联。它使用对象时会发出尖叫声。做的事:

var obj = {};
obj[46] = { sel:46, min:0,  max:52 };
obj[666] = { whatever:true };

// This is what for..in is for
for (var prop in obj) {
  console.log(obj[prop]);
}

Maybe some utility stuff like this can help:

也许像这样一些实用的东西能帮上忙:

window.WidthRange = (function () {
  var obj = {};
  return {
    getObj: function () {return obj;}
    , add: function (key, data) {
        obj[key] = data;
        return this; // enabling chaining
      }
  }
})();

// Usage (using chaining calls):
WidthRange.add(66, {foo: true})
.add(67, {bar: false})
.add(69, {baz: 'maybe', bork:'absolutely'});

var obj = WidthRange.getObj();
for (var prop in obj) {
  console.log(obj[prop]);
}

#9


0  

Seems to work.

似乎工作。

var widthRange = new Array();
widthRange[46] = { sel:46, min:0,  max:52 };
widthRange[66] = { sel:66, min:52, max:70 };
widthRange[90] = { sel:90, min:70, max:94 };

for (var key in widthRange)
{
    document.write(widthRange[key].sel + "<br />");
    document.write(widthRange[key].min + "<br />");
    document.write(widthRange[key].max + "<br />");
}

#10


0  

I wrote a function what works fine with every instance of Objects (Arrays are those).

我编写了一个函数,它对每个对象实例(数组就是这些对象)都适用。

Object.prototype.toArray = function()
{
    if(!this)
    {
      return null;
    }

    var c = [];

    for (var key in this) 
    {
        if ( ( this instanceof Array && this.constructor === Array && key === 'length' ) || !this.hasOwnProperty(key) ) 
        {
            continue;
        }

        c.push(this[key]);
    }

    return c;
};

Usage:

用法:

var a   = [ 1, 2, 3 ];
a[11]   = 4;
a["js"] = 5;

console.log(a.toArray());

var b = { one: 1, two: 2, three: 3, f: function() { return 4; }, five: 5 };
b[7] = 7;

console.log(b.toArray());

Output:

输出:

> [ 1, 2, 3, 4, 5 ]
> [ 7, 1, 2, 3, function () { return 4; }, 5 ]

It may be useful for anyone.

它可能对任何人都有用。

#11


0  

... ????

…? ? ? ?

Alternatively, if you have a list of items you want to use...

或者,如果你有一个你想要使用的项目列表……

var range = [46, 66, 90]
    , widthRange=[]
    , write=[];

    widthRange[46] = { min:0, max:52 }; 
    widthRange[66] = { min:52, max:70 }; 
    widthRange[90] = { min:70, max:94 }; 

for(var x=0; x<range.length; x++){var key, wr;

    key = range[x];

    wr = widthRange[key] || false;

    if(wr===false){continue;}

    write.push(['key: #',key, ', min: ', wr.min, 'max:', wr.max].join(''));

    }