Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
660 views
in Technique[技术] by (71.8m points)

javascript - Dynamically create object keys in IE 11 (Expected identifier, string or number, not a comma issue)

I'm looking for a solution that creates object keys (is that worded correctly?) dynamically.

Arbitrary example, but this works in chrome and firefox

var weeks = {}
for(var i = 0; i < 5; i++){
    $.extend(weeks, {["week" + i] : (i * 2)}
}

//weeks = {"week0":0,"week1":2,"week2":4,"week3":6,"week4":8}

Or alternative arbitrary example

var object = {
  ["a" + 50]: "value"
}

The problem seem to be rooted in the [] operator, but I don't understand how or why this problem only occurs in IE. I have not tested in previous versions to IE11, but I would assume the problem would persist there aswell.

Since the problem seem to be with the [] operator itself, creating my keys in a variable and then shoving that variable into my [] wouldn't do anything to fix the problem, so I seem to be both out of ideas and keywords to google.

So is there a way to dynamically create object keys in IE?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

IE11 is not a "modern" web browser in the same way Chrome, Firefox or even Edge is. It doesn't support the new "object literal extensions" from ES6 (ES2015).

The syntax you are using is called "computed property keys", you cannot use it in IE11. You need to do this the "old fashioned" way.

var weeks = {};

for(var i = 0; i < 5; i++){
    var tmp = {};
    tmp["week" + i] = i*2;

    $.extend(weeks, tmp);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...