简体   繁体   中英

Javascript: Losing object reference while reading array items

How to read object from array, or what I'm doing wrong?

Here is my array map with object as key:

var nj = new RegExp("nj","g");
var replaceMap = {nj:"ň"};

But while looping the array I can't get valid object reference.

for (var replaceValue in replaceMap) {
   text = text.replace(replaceValue, replaceMap[replaceValue]);
}

When replace is performing then it replaces only one instance of search text - RegExp object modifier for global match ("g") is ignored. I suppose, that I didn't get a valid object reference in replaceValue. When I used nj variable replace operation then it works fine.

Thanks in advance.

Reason:

When you refer something like for(var x in o){...}, then x is a javascript string, and not an object.

So in your case it is "nj" and not RegExp object nj

hence only the first match gets replaced.

You can test it like this:

var a=new RegExp("kk","g");
var mymap={a:"jjj"};

for(var k in mymap){
console.log(k+"  "+typeof k);
}

The console output will give you the typeof the key

text = text.replace(/nj/g, 'ň');

这应该执行相同的事情

Check this in your browser console (press F12 in Chrome of Firefox):

>var aa="hello";
undefined
>var replaceMap={aa: "Hello2"}
undefined
>replaceMap
Object {aa: "Hello2"}

This is the equivalent code:

var aa="hello";
var replaceMap={};
replaceMap.aa="Hello2";

replace.aa has nothing to do with variable aa

But you can fix it interchanging keys and values in your map:

var replaceMap = {"ň": nj};
for (var replaceValue in replaceMap) {
   text = text.replace(replaceMap[replaceValue], replaceValue);
}

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