如何循环遍历JavaScript中的编号变量?

huangapple go评论69阅读模式
英文:

how do you loop through javascript numbered variables?

问题

如何遍历JavaScript中的编号变量?

let count = 5;

var test1 = "test1";
var test2 = "test2";
var test3 = "test3";
var test4 = "test4";
var test5 = "test5";

for (let i = 0; i < count; i++)
{
    console.log(eval("test" + (i + 1)));
}

期望看到变量名...
test1
test2
test3
test4
test5

英文:

how do you loop through javascript numbered variables?

let count = 5;

var test1 = &quot;test1&quot;
var test2 = &quot;test2&quot;
var test3 = &quot;test3&quot;
var test4 = &quot;test4&quot;
var test5 = &quot;test5&quot;

for (let i = 0; i &lt; count; i++)
{
    console.log(test{i});  //no that don&#39;t work
}

tired a few different for loops I found but could not get anything to work.
New to all of this.

expecting to see the variable names...
test1
test2
test3
test4
test5

Maybe I'm asking the wrong question. The problem with an Object or an Array is when I assign it to Local Storage and go back and want to delete that item, if it's in a array or object I delete everything using removeItem(keyName). That is why I wanted to created a new name/variable for each event. That way I can delete the item without removing everything else. –
jondavis4

答案1

得分: 1

问题出在将对象或数组分配给本地存储后,当我返回并想要删除该项目时,如果它在数组或对象中,我会使用removeItem(keyName)删除所有内容。这就是为什么我想为每个事件创建一个新的名称/变量。这样我就可以删除项目而不影响其他内容。

也许需要一些进一步的改进,但我认为这可以解决所述的问题:

function saveEvent(event){
    if(localStorage.getItem("events") != null){
        const events = JSON.parse(localStorage.getItem("events"));
        events[event.name] = event.value;
        localStorage.setItem("events", JSON.stringify(events));
    }else{
        const events = JSON.stringify({ "event1": "event description?", "event2": "another description?" });
        localStorage.setItem("events", events);
    }
}

function deleteEvent(eventName){
    if(localStorage.getItem("events") != null){
        const events = JSON.parse(localStorage.getItem("events"));
        events[eventName] = undefined;
        localStorage.setItem("events", JSON.stringify(events));
    }else{
        console.error("Events doesn't exist!");
    }
}

也许需要一些解释:

通过使用saveEvent(event),您可以将新事件保存到localStorage中的现有对象,或者如果不存在,则创建一个新对象。实际事件对象的结构显然取决于您的需求。

通过使用deleteEvent(eventName),如果存在localStorage中,会从localStorage中读取对象,并从检索到的对象中删除事件。之后,修改后的对象再次保存在localStorage中。

英文:

The problem with an Object or an Array is when I assign it to Local Storage and go back and want to delete that item, if it's in a array or object I delete everything using removeItem(keyName). That is why I wanted to created a new name/variable for each event. That way I can delete the item without removing everything else.

Probably needs some more refinement, but i think this would solve the issue stated:

function saveEvent(event){
    if(localStorage.getItem(&quot;events&quot;) != null){
        const events = JSON.parse(localStorage.getItem(&quot;events&quot;));
        events[event.name] = event.value;
        localStorage.setItem(&quot;events&quot;,events)
    }else{
        const events = JSON.stringify({ &quot;event1&quot;: &quot;event description?&quot;, &quot;event2&quot;: &quot;another description?&quot;})
        localStorage.setItem(&quot;events&quot;,events)
    }
}

function deleteEvent(eventName){
    if(localStorage.getItem(&quot;events&quot;) != null){
        const events = JSON.parse(localStorage.getItem(&quot;events&quot;))
        events[eventName] = undefined;
        localStorage.setItem(&quot;events&quot;,JSON.stringify(events))
    }else{
        console.error(&quot;Events doesn&#39;t exist!&quot;)
    }
}

Maybe some explanation:

By using saveEvent(event) you would be able to either save a new event to the existing object inside the localStorage or create a new object if none exists. What the actual event-object would look obviously depends on your needs.

By using deleteEvent(eventName) the Object is read from the localStorage, if it exists, and the event is being removed from the retrieved object. After that the modified object is saved again inside the localStorage.

答案2

得分: 0

以下是翻译好的部分:

"与您当前代码最相似的解决方案是使用模板变量(反引号)和 eval 函数,它将字符串转换为变量名。

let count = 5;
 
var test1 = "test1"
var test2 = "test2"
var test3 = "test3"
var test4 = "test4"
var test5 = "test5"

for (let i = 1; i <= count; i++)
{
    console.log(eval(`test${i}`));  
}
英文:

The solution most similar to your current code would be to use template variables (backticks) and the eval function, which turns a string into a var name.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let count = 5;
 
var test1 = &quot;test1&quot;
var test2 = &quot;test2&quot;
var test3 = &quot;test3&quot;
var test4 = &quot;test4&quot;
var test5 = &quot;test5&quot;

for (let i = 1; i &lt;= count; i++)
{
    console.log(eval(`test${i}`));  
}

<!-- end snippet -->

答案3

得分: -1

以下是您要求的代码部分的翻译:

let count = 5;

var test1 = "test1";
var test2 = "test2";
var test3 = "test3";
var test4 = "test4";
var test5 = "test5";
var test345 = "test7262";
// 获取所有窗口键 - 可能有很多
// 所有全局键
let keys = Object.keys(window);
// 很多 console.log(keys, keys.length);
/*
const PATTERN = 'test'; // 用于筛选的模式(如果 "testmealso" 是一个则可能需要修改
let filteredKeys = keys.filter(name => name.includes(PATTERN)); // 一种方式
*/

// 或许更好的方式:
const regex = new RegExp("^test[^\\d]+", 'g');
/* 解释如下
^test - 以 test 开始
[^character_group] 否定:匹配不在 character_group 中的任何单个字符。
\d 匹配任何十进制数字。
*/
console.log(window["test345"]); // 一个值的输出
// 现在使用正则表达式进行筛选
const matchedSites = keys.filter((key) => key.match(regex));
console.log(matchedSites);

//console.log(filteredKeys);    
// 它们是什么:
matchedSites.forEach(key => {
  // 记录键/值对
  console.log(key, window[key]);
});

希望这有助于您理解代码部分的内容。

英文:

Explained in-line in the code.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let count = 5;

var test1 = &quot;test1&quot;;
var test2 = &quot;test2&quot;;
var test3 = &quot;test3&quot;;
var test4 = &quot;test4&quot;;
var test5 = &quot;test5&quot;;
var test345 = &quot;test7262&quot;;
// get all the window keys - might be a lot
// all the global keys
let keys = Object.keys(window);
// lots of them console.log(keys, keys.length);
/*
const PATTERN = &#39;test&#39;; // pattern to filter into (might need work if &quot;testmealso&quot; is one
let filteredKeys = keys.filter(name =&gt; name.includes(PATTERN)); // one way
*/

// better way perhaps:
const regex = new RegExp(&quot;^test[^\d]+&quot;, &#39;g&#39;);
/* explained as
^test - starts with test
[^character_group] Negation: Matches any single character that is not in character_group.
\d Matches any decimal digit.
*/
console.log(window[&quot;test345&quot;]); // the value of one
// filter then now on the regex
const matchedSites = keys.filter((key) =&gt; key.match(regex));
console.log(matchedSites);

//console.log(filteredKeys);    
// what are they:
matchedSites.forEach(key =&gt; {
  // log key/value pairs
  console.log(key, window[key]);
});

<!-- end snippet -->

答案4

得分: -2

正确答案是:

let count = 5;
var tests = ["test1", "test2", "test3", "test4", "test5"];

for (let i = 0; i < count; i++) {
    console.log(tests[i]);
}
英文:

The correct answer is

let count = 5;
var tests = [&quot;test1&quot;, &quot;test2&quot;, &quot;test3&quot;, &quot;test4&quot;, &quot;test5&quot;];

for (let i = 0; i &lt; count; i++) {
    console.log(tests[i]);
}

huangapple
  • 本文由 发表于 2023年6月30日 05:05:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76584603.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定