简体   繁体   中英

for loop gives only last value in javascript

I have created variable outside to get values from inside but I only get last value in both variables.

 var categoryProductid; var PPProducttitle; for (var key in UpdatedCategory) { const actual = UpdatedCategory[key] var categoryProductid = actual.id; var PPProducttitle = actual.title; console.log(PPProducttitle) console.log(categoryProductid) } console.log(PPProducttitle) console.log(categoryProductid)

when I do console.logs() from inside and outside of for loop I get two different values.

Any help will be appreciated thank you!!!!!

I'm going to assume that UpdatedCategory is an object (if it's an array, please see my answer here for what to use instead of for-in to loop through it).

The basic problem with that code is that you're assigning to the same variable over and over. The reason it's the same variable is that var doesn't have block scope, so the var part of var categoryProductid = actual.id; is completely ignored (and similar for var PPProducttitle = actual.title; ). Instead, you're reusing the variables you declared prior to the for loop.

A variable can only hold one value, so when you assign a new value to it, it no longer holds the old value.

If you want to hold multiple values with a variable, you can assign a container to it that can hold multiple values, such as an array, an object, a Map , or a Set .

You haven't said what end result you want, but here's an example that creates two arrays and fills them with the id and title of the products from UpdatedCategory :

 // Again, I'm assuming `UpdatedCategory` is an object: const UpdatedCategory = { a: { id: 1, title: "a", }, b: { id: 2, title: "b", }, c: { id: 3, title: "c", }, }; // `[]` creates a new empty array. // We can use `const` to declare these because we never change their // value (they only ever refer to a single array), but you could use // `let` if you preferred. Don't use `var` in new code, it's deprecated. // Note: I've renamed these slightly to: // 1. Stick to standard naming conventions // * Initial capitals are used primarily for constructor functions // * Variables referring to arrays are generally plurals // 2. Be consistent in capitalization const categoryProductIds = []; const ppProductTitles = []; for (var key in UpdatedCategory) { // Get this property value const actual = UpdatedCategory[key]; // Push the `id` and `title` into the relevant arrays categoryProductIds.push(actual.id); ppProductTitles.push(actual.title); } // Show the contents of the arrays console.log(ppProductTitles); console.log(categoryProductIds);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM