简体   繁体   中英

Creating new array out of already existing in javascript

I have an array filled with HTML objects - in my case all of them are li items. I have to create new array with textContent from these lis . So I have two arrays:

A = [li, li, li, li, li];
B = [];

I've wrote such function:

function addContent() {
  for (let i = 0; i < A.length; i++) {
    let newConent = A[i].textContent;
    B.push(newConent);
  }
}

So my question is: is there any known method or more optimal way to do that? I'm interested in JavaScript approach.

Thanks in advance (x

If A is an array, you can do it like this:

B = A.map(li => li.textContent)

But I don't think you really have an array. If you get elements by method like querySelectorAll , you need to make an array for it.

 const lis = document.querySelectorAll('li') const A = [] for (let i = 0; i < lis.length; i++) { A.push(lis[i]) } const B = A.map(li => li.textContent) console.log(B) 
 <li>a</li> <li>b</li> <li>c</li> 

You can use .map() to iterate over array of list items and return desired property values:

 const list = [...document.querySelectorAll("li")]; const text = list.map(li => li.textContent); console.log(text); 
 <ul class="list"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> 

Alternatively, you can also use a for...of loop:

 const list = document.querySelectorAll("li"); const text = []; for (item of list) text.push(item.textContent); console.log(text); 
 <ul class="list"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> 

You can use Array.prototype.map()

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

 let lis = Array.from(document.querySelectorAll('li')); let texts = lis.map(li => li.textContent); console.log(texts); 
 <ul> <li>First</li> <li>Second</li> <li>Third</li> </ul> 

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