简体   繁体   中英

Convert binary integer array to string array in Javascript

I have a integer array

array = [1,1,1,1,0,0,0,0]

that I want to convert to a string array based on the following logic:

for(var index in arr){
   if(arr[index] == 0){
      arr[index] == 'Closed'
   }
   else{
      arr[index] == 'Open'
   }
}

In order to get the following output

arr = ['open','open','open','open','closed','closed','closed','closed']

But the code is not executing correctly. Can you not assign strings to arrays in Javascript? Any help would be appreciated.

You have a typo

arr[index] == 'Closed'
           ^

And here

arr[index] == 'Open'
           ^

There you're making a comparison rather than an assignation.

Another alternative to accomplish your requirement is using the function map :

This approach will create a new array

 const array = [1,1,1,1,0,0,0,0], result = array.map(n => n === 0 ? 'closed' : 'open'); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

A little shorter using coercion from boolean (1 = true, 0 = false)

 const array = [1,1,1,1,0,0,0,0], result = array.map(n => n ? 'open' : 'closed'); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

You are using comparison operations rather than assigning the value, it should be arr[index] = 'Open' rather than arr[index] == 'Open'

You can use Array.map to test the value of the array items. The return value is a new array of the updated value

es5 example

var converted = arr.map(function(value){ if (value ==0) { return 'closed'; } return 'open'; });

es6

const converted = arr.map(value => value === 0 ? 'closed' : 'open');

you can use map();

 array = [1,1,1,1,0,0,0,0]; const result = array.map(el => el === 1 ? "open" : "close"); console.log(result); 

You are using == rather than = in some places. Double equals is used for comparison, like checking if a cup has orange juice in it. Single equals is used for setting a variable, like pouring orange juice into the cup. The correct code should be:

for(var index in arr) {
    if(arr[index] == 0) {
        arr[index] = 'Closed'
    } else {
        arr[index] = 'Open'
    }
}

Another thing to consider is that it is generally bad practice to change the type of an array, even it is possible in JavaScript. The reason is that it is then difficult if, later on in your code, you want to get the original binary array back.

Best wishes, Luke.

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