次のようなループがあります。
for (var prop in obj) {
if (obj.hasOwnProperty(prop) {
// Here need operation only for first iteration (1)
// Other operations
}
}
(1) の最初の反復をどのように特定できますか?
次のようなループがあります。
for (var prop in obj) {
if (obj.hasOwnProperty(prop) {
// Here need operation only for first iteration (1)
// Other operations
}
}
(1) の最初の反復をどのように特定できますか?
可能であれば、ループの外に移動します。
do_one_time_thing();
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
// Other operations
}
}
それ以外の場合は、フラグを設定し、最初の繰り返しの後に下げます。
var first_iteration = true;
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
if (first_iteration) {
do_one_time_thing();
first_iteration = false;
}
// Other operations
}
}
ループ カウンターがないため、これを自分で追跡する必要があります。
var first = true;
for (var prop in obj) {
if (obj.hasOwnProperty(prop) {
if (first) {
first = false;
// Here need operation only for first iteration (1)
}
// Other operations
}
}
プロパティが予測可能な順序でリストされることは保証されていません (他の人が言ったように)。
したがって、 Object.keysを使用してオブジェクト プロパティを配列として取得し、その配列を並べ替えて最初の要素を取得できます。
var firstProperty = Object.keys(obj).sort()[0];
// firstValue = obj[firstProperty];