[英]How can I do array to assign another array and trim?
I have textarea and textare jsccode as the following : 我有textarea和textare jsccode如下:
var checkName = (document.getElementById("List").value);
var tempcheckNames = checkName.split('\n');
and assign array another array with trim. 并分配另一个带有修剪的数组。
for (var i = 0; i < tempcheckNames.length;i++){
checkNames = tempcheckNames[i].trim().split('\n');
}
But checkNames is empty because assign with not array ? 但是checkNames为空,因为没有分配数组?
So I want to trim from textarea value (I did textarea value split so my array is textarea value ('\\n') 所以我想从textarea值中修剪(我做了textarea值拆分,所以我的数组是textarea值('\\ n')
Define checkNames
as an array, use .push()
to add items to checkNames
array within for
loop, remove call to .split()
within for
loop 限定
checkNames
作为数组,使用.push()
将项目添加到checkNames
内阵列for
循环,除去调用.split()
内for
环
for (var i = 0, checkNames = [] /* define `checkNames` as an array */
; i < tempcheckNames.length
; i++) {
checkNames.push(tempcheckNames[i].trim());
// .split('\n'); `.split()` not needed here
}
You can push the values to an array to get all the split values 您可以将值推送到数组以获取所有拆分值
var btn = document.getElementById('btn-show'); btn.addEventListener('click', btnShow); function btnShow (e) { var checkName = (document.getElementById("list").value); var tempcheckNames = checkName.split('\\n'); var checkNames = []; for (var i = 0; i < tempcheckNames.length;i++){ checkNames.push(tempcheckNames[i].trim()); } alert(checkNames); }
<textarea id='list'> </textarea> <button id='btn-show'>Show</button>
Functional approach using Array.map 使用Array.map的功能方法
var btn = document.getElementById('btn-show'); btn.addEventListener('click', btnShow); function btnShow (e) { var checkName = (document.getElementById("list").value); const checkNames = checkName.split('\\n').map((name) => name.trim() ); alert(checkNames); }
<textarea id='list'> </textarea> <button id='btn-show'>Show</button>
这样,时间更短
var checkName = document.getElementById("List").value.split("\n").map(element => element.trim());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.