Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/428.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 证明数组索引中的文本的合理性_Javascript_Arrays - Fatal编程技术网

Javascript 证明数组索引中的文本的合理性

Javascript 证明数组索引中的文本的合理性,javascript,arrays,Javascript,Arrays,如果您有给定的数组,您将如何为给定的空间证明文本的合理性?假设每个索引中需要20个字符,包括空格 示例数组 ['Hello there champ', 'example text', 'one two three' ] 然后将结果调整到给定的长度(本例为20) 如何将第一个数组格式化为第二个数组 您可以拆分字符串并添加到除最后一个之外的所有项目中,直到达到所需的长度 var数组=['Hello there champ','example text','一两三'], 长度=20; fo

如果您有给定的数组,您将如何为给定的空间证明文本的合理性?假设每个索引中需要20个字符,包括空格

示例数组

['Hello there champ', 
 'example text', 
 'one two three'
]
然后将结果调整到给定的长度(本例为20)


如何将第一个数组格式化为第二个数组

您可以拆分字符串并添加到除最后一个之外的所有项目中,直到达到所需的长度

var数组=['Hello there champ','example text','一两三'],
长度=20;
forEach(函数(a,i,aa){
var temp=a.split(“”),
l=长度-温度连接('')。长度;
while(l){
温度(功能(b、j、bb){
如果(j+1==bb.长度){
返回;
}
如果(l){
bb[j]+='';
l--;
返回true;
}
});
}
aa[i]=临时连接(“”);
});

console.log(数组)将其拆分为单独的操作,首先将数组映射回原处,然后在单词边界上拆分,并修剪掉已经存在的空格

那只是一个计数问题。数一数单词和字符,计算出应该有多少空格,并在空格数不均匀时在最后一个空格中添加一些内容

var-arr=[
“你好,冠军”,
“示例文本”,
“一二三”
]
函数调整(a,n){
返回a.map(x=>{
var words=x.split(/\b/).filter(y=>y.trim().length)
var total=单词。连接(“”)。长度;
变量空间=(n-总计)/(words.length-1);
var fill=新数组(数学层(空格)+1);
var结果=单词。连接(填充);
return result.length==n?结果:result.replace(/\s([^\s]*)$/,“$1”);
});
}

控制台日志(调整(arr,20))这个想法是确定需要多少空格,并将它们平均分配到现有的空白处(单词之间的空格)

var arr=['Hello there champ','example text','一两三'];
var newArr=[];
arr.forEach(v=>{
var words=v.split(/\s+/);
所需变量=20个字。连接(“”)长度;
var gaps=单词长度-1;
var perGap=数学地板(需要/间隙);
var extra=所需-(每个间隙*间隙);
var newValue=words.join(数组(perGap+1.join)(“”);
if(extra){//在最后一个间隙中添加所需的额外空格
newValue=newValue.replace(新的RegExp(words[words.length-1]+“$”),数组(extra+1)。join(“”+words[words.length-1]);
}
newArr.push(newValue);
});

newArr.forEach(v=>console.log(v))['Hello there champ', 'example text', 'one two three' ]