简体   繁体   English

将数组转成字符串,用分隔符分隔字符串 - JavaScript

[英]Turn Array Into String, Separate String With Separator - JavaScript

Define a function, myJoin , that accepts up to two arguments:定义一个函数myJoin ,它最多接受两个参数:

  1. array
  2. separator (string, optional) separator (字符串,可选)

myJoin should return a string with all of the elements from the array joined together. myJoin应该返回一个字符串,该字符串将数组中的所有元素连接在一起。 The separator should separate the joined elements:分隔符应分隔连接的元素:

myJoin(['a', 'b', 'c'], '+'); // => "a+b+c"

If separator is undefined, use ',' as the default separator.如果未定义分隔符,则使用','作为默认分隔符。

myJoin(['Peter', 'Paul', 'Mary']); // => "Peter,Paul,Mary"

If any elements in the array are undefined or null , they should be replaced with an empty string in the returned string.如果数组中的任何元素是undefinednull ,则应将它们替换为返回字符串中的空字符串。

myJoin(['hello', undefined, 'world'], '-'); // => "hello--world"

I can't use the built-in join method.我无法使用内置的join方法。

Link to codepen for testing 链接到用于测试的 codepen

So far I have tried:到目前为止,我已经尝试过:

function myJoin (array, separator) {

  let newString = "";

  if (separator = undefined) {
    separator === ",";
  }

  else {

    for (let i = 0; i < array.length; i++) {
      newString = i + separator;
    }

  }

  newString = array.toString();

  return newString;

}

console.log(myJoin(['a', 'b', 'c'], '+'));

^ This is not combining the elements of the string together with the separator, and is actually returning a,b,c twice. ^ 这不是将字符串的元素与分隔符组合在一起,实际上是返回a,b,c两次。 Any idea why?知道为什么吗?

EDIT : First update to code after @Jonas Wilms' suggestions:编辑:在@Jonas Wilms 的建议之后第一次更新代码:

function myJoin (array, separator) {

  let newString = "";

  if (separator === undefined) {
    separator === ",";
  }

  for (let i = 0; i < array.length; i++) {
    newString += array[i] + separator;
  }

  return newString;

}

This seems to be working in my VS Code console but not in the CodePen.这似乎在我的 VS Code 控制台中有效,但在 CodePen 中无效。

try尝试

array.reduce( (s,x,i) => s+(i>0 ? separator : '') + (x==null ? '' : x), '') 

 function myJoin(array, separator=',') { return array.reduce( (s,x,i) => s+(i>0 ? separator : '') + (x==null ? '' : x), '') } console.log( myJoin(['a', 'b', 'c'], '+') ); console.log( myJoin(['Peter', 'Paul', 'Mary']) ); console.log( myJoin(['hello', undefined, 'world'], '-') );

We use here standard js functionalities: arrow functions , array reduce and ternary operator .我们在这里使用标准的 js 功能: 箭头函数数组归约三元运算符 If i>0 (not true only for first element) we add separator to output string s .如果i>0 (不是仅对第一个元素为真),我们将分隔符添加到输出字符串s If x is undefined or null we add to s empty string - or x value in other case.如果x未定义或为空,我们将添加到s空字符串 - 或在其他情况下添加x值。

A few hints:一些提示:

  • Don't mix up the assignment ( = ) and comparison ( === ) operators.不要混淆赋值 ( = ) 和比较 ( === ) 运算符。 if(a = b) is a mistake in 99% of the cases. if(a = b)在 99% 的情况下都是错误的。

  • array.toString() does call array.join() internally, I'd consider that as cheating, also I'm not sure what you want to achieve with that (I mean newString should already contain the wanted result if you do the loop correctly, shouldn't it?) array.toString()确实在内部调用array.join() ,我认为这是作弊,我也不确定你想用它实现什么(我的意思是newString应该已经包含想要的结果,如果你做循环正确,不是吗?)

  • i is the index in your array to get the value at that position use array[i] . iarray的索引,用于获取该位置的,使用array[i]

  • I don't think that your loop should be in the else { branch, I don't think you need that else at all (as you always want to join the array by looping over it).我不认为你的循环应该在else {分支中,我认为你根本不需要else (因为你总是想通过循环加入数组)。

  • with newString = you reassign newString and loose the previous value, you might want to use newString += to append a value to it.使用newString =重新分配newString并丢失以前的值,您可能希望使用newString +=为其附加一个值。

Use map and forEach with a template string like so:mapforEach与模板字符串forEach使用,如下所示:

 function myJoin(arr, sep = ",") { arr = arr.map(e => [undefined, null].includes(e) ? "" : e); var result = ""; arr.forEach((e, i) => result += `${i ? sep : ""}${e}`); return result; } console.log(myJoin(['Peter', undefined, 'Paul', null, 'Mary', 'Jack'], "-"));

ES5 syntax: ES5 语法:

 function myJoin(arr, sep) { sep = sep || ","; arr = arr.map(function(e) { return [undefined, null].includes(e) ? "" : e; }); var result = ""; arr.forEach(function(e, i) { result += (i ? sep : "") + e; }); return result; } console.log(myJoin(['Peter', undefined, 'Paul', null, 'Mary', 'Jack'], "-"));

 function myJoin(array, separator=',') { let str = ''; for (let i = 0; i < array.length; i++) { if (array[i] !== null && array[i] !== undefined) str += array[i]; if (i < array.length - 1) str += separator; } return str; } console.log(myJoin(['a','b','c'])); console.log(myJoin(['a','b','c'], '+')); console.log(myJoin(['a',null,'c'], '-')); console.log(myJoin(['a','b',undefined], '.'));

Use default syntax to set the seperator ||使用默认语法设置分隔符|| The a forEach taking in value , index , array Test for last element. a forEach接受valueindexarray测试最后一个元素。

 function myJoin (array, separator) { let newString = ""; separator = separator||','; array.forEach((a,i,arr) => { newString += `${a}${(i < arr.length-1) ? separator : ''}`; }); return newString; } console.log(myJoin(['a', 'b', 'c'], '+')); console.log(myJoin(['a', 'b', 'c'])); console.log(myJoin(['a', 'b', 'c'], '-'));

You can use Array.reduce() to join your array.您可以使用Array.reduce()加入您的数组。

 let arr = ['a', 'b', undefined, 'c', 'd', null, 'e']; myJoin = (arr, separator = ',') => arr.reduce((acc, val, i) => acc + ([undefined, null].indexOf(val) >= 0 ? '' : val) + (i < arr.length - 1 ? separator : ''), ""); console.log('myJoin(arr): ', myJoin(arr)); console.log('myJoin(arr, "+"): ', myJoin(arr, '+')); console.log('arr.join("+"): ', arr.join('+'));

Hope this helps,希望这可以帮助,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM