For..In pętle w parach wartości JavaScript-klucz
Zastanawiałem się, czy jest sposób na zrobienie czegoś takiego jak pętla PHP foreach
w JavaScript. Funkcjonalność, której szukam, to coś w stylu tego fragmentu PHP:
foreach($data as $key => $value) { }
Patrzyłem na pętlę JS for..in
, ale wydaje się, że nie ma sposobu, aby określić as
. Jeśli zrobię to z' normalną ' pętlą for (for(var i = 0; i < data.length; i++
), czy istnieje sposób, aby pobrać pary klucz = > wartość?
14 answers
for (var k in target){
if (target.hasOwnProperty(k)) {
alert("Key is " + k + ", value is" + target[k]);
}
}
hasOwnProperty
służy do sprawdzania, czy twoja target
naprawdę posiada tę właściwość, zamiast dziedziczyć ją po swoim prototypie. Nieco prostsze byłoby:
for (var k in target){
if (typeof target[k] !== 'function') {
alert("Key is " + k + ", value is" + target[k]);
}
}
Sprawdza tylko, czy k
nie jest metodą (tak jakby target
jest array
otrzymasz wiele metod, np. indexOf
, push
, pop
,itd.)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-30 17:15:16
Nikt nie wspomniał Object.keys
więc o tym wspomnę.
Object.keys(obj).forEach(function (key) {
// do something with obj[key]
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-20 17:12:12
for in
będzie działać dla Ciebie. Jeśli myślisz o obiekcie Jak o mapie:
for(key in obj){
// The key is key
// The value is obj[key]
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-30 10:37:22
Jeśli możesz użyć ES6 natywnie lub z Babel (kompilator js), możesz wykonać następujące czynności:
let test = {a: 1, b: 2, c: 3};
for (let [key, value] of Object.entries(test)) {
console.log(key, value);
}
Które wydrukuje to wyjście:
a 1
b 2
c 3
Metoda Object.entries()
zwraca tablicę własnych par wyliczalnych danego obiektu [key, value]
, w tej samej kolejności, jaką zapewnia pętla for...in
(różnica polega na tym, że pętla for-in wylicza również właściwości w łańcuchu prototypów).
- obiekt.wpisy dokumentacja
- dla...z dokumentacji
- przypisanie destrukcji dokumentacja
- Wyliczalność i własność nieruchomości dokumentacja
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-18 07:58:51
var obj = {...};
for (var key in obj) {
var value = obj[key];
}
Składnia php jest tylko cukrem.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-05 19:00:00
Zakładam, że wiesz, że i
jest kluczem i że możesz uzyskać wartość przez data[i]
(i po prostu chcesz skrót do tego).
Ecmascript5 forEach
[MDN] dla tablic (wygląda na to, że macie tablicę):
data.forEach(function(value, index) {
});
Dokumentacja MDN zapewnia shim dla przeglądarek, które go nie obsługują.
Oczywiście nie działa to dla obiektów, ale można utworzyć dla nich podobną funkcję:
function forEach(object, callback) {
for(var prop in object) {
if(object.hasOwnProperty(prop)) {
callback(prop, object[prop]);
}
}
}
Ponieważ otagowałeś pytanie z jquery , jQuery zapewnia $.each
[docs] który zapętla zarówno struktury tablicowe, jak i obiektowe.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-30 10:44:22
for (var key in myMap) {
if (myMap.hasOwnProperty(key)) {
console.log("key =" + key);
console.log("value =" + myMap[key]);
}
}
W javascript, każdy obiekt ma kilka wbudowanych par klucz-wartość, które mają meta-informacje. Po zapętleniu wszystkich par klucz-wartość dla obiektu również je zapętlasz. Użycie metody hasOwnProperty() je filtruje.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-19 15:26:04
Możesz użyć for..in
do tego.
for (var key in data)
{
var value = data[key];
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-30 10:38:04
ES6 dostarczy mapę.prototyp.forEach (callback), które mogą być użyte w ten sposób
myMap.forEach(function(value, key, myMap) {
// Do something
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-16 13:51:50
Możesz użyć do tego pętli 'for in':
for (var key in bar) {
var value = bar[key];
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-30 10:38:24
Poniżej znajduje się przykład, który jest jak najbardziej zbliżony.
for(var key in data){
var value = data[key];
//your processing here
}
Jeśli używasz jQuery Zobacz: http://api.jquery.com/jQuery.each/
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-30 10:39:59
let test = {a: 1, b: 2, c: 3};
Object.entries(test).forEach(([key, value]) => console.log(key, value))
// a 1
// b 2
// c 3
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-17 11:56:54
Tak, możesz mieć tablice asocjacyjne również w javascript:
var obj =
{
name:'some name',
otherProperty:'prop value',
date: new Date()
};
for(i in obj)
{
var propVal = obj[i]; // i is the key, and obj[i] is the value ...
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-30 10:38:44
var global = (function() {
return this;
})();
// Pair object, similar to Python
function Pair(key, value) {
this.key = key;
this.value = value;
this.toString = function() {
return "(" + key + ", " + value + ")";
};
}
/**
* as function
* @param {String} dataName A String holding the name of your pairs list.
* @return {Array:Pair} The data list filled
* with all pair objects.
*/
Object.prototype.as = function(dataName) {
var value, key, data;
global[dataName] = data = [];
for (key in this) {
if (this.hasOwnProperty(key)) {
value = this[key];
(function() {
var k = key,
v = value;
data.push(new Pair(k, v));
})();
}
}
return data;
};
var d = {
'one': 1,
'two': 2
};
// Loop on your (key, list) pairs in this way
for (var i = 0, max = d.as("data").length; i < max; i += 1) {
key = data[i].key;
value = data[i].value;
console.log("key: " + key + ", value: " + value);
}
// delete data when u've finished with it.
delete data;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-08-30 14:08:33