如何在没有原生javascript的情况下手动实现连接功能?

问题描述 投票:0回答:4

我是一名JavaScript初学者,这是我要解决的5个编码问题。

1。声明一个名为myName的变量,并将其分配给填充有两个字符串的数组:1)您的名字和2)您的名字。

2。声明一个名为join的函数,该函数可以接受两个输入:1)一个数组和2)一个分隔符字符串。分隔符字符串是可选的。

3.join将输入数组的所有元素与输入字符串连接起来并返回结果。 join的输出始终是字符串。

4。如果未提供分隔符,则默认分隔符应为字符串空间''。如果没有提供输入数组或该数组为空,则join应该返回一个空字符串''。

5。您不能对数组使用内置的join方法,我们强烈建议您避免使用其他内置的方法。


//到目前为止,我已经在下面编写了一些代码,看来我已经完成了1〜3。但是,我不知道要解决4和5。如何解决它们?

//错误消息:当不提供分隔符时,join函数应默认为使用空格;如果不提供数组,则应返回空字符串

var myName = ["FirstName", "LastName"];

function join(arr,sep) {
  result = arr.join(sep);
  return result;
};
javascript arrays function separator
4个回答
1
投票

4)您可以设置参数的默认值,该参数将在不传递任何值时使用:

function join(arr = [], sep = '') {
  if (arr.length === 0) {
        return "";
  }
};

5)如果无法使用内置方法,则可以编写join的代码:

function join(arr, sep = '') {
  var result = "";
  for (let i = 0; i < arr.length - 1; i++) {
        result += arr[i];
        result += sep;
  }
  result += arr[arr.length - 1];
  return result;
};

0
投票
var myName = ["firstName", "lastName"];
// note the sep = " ", this is JS's default value syntax
// See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters
function join(arr, sep = " ") {
    // if arr is not an instance of an array
    // then we return an empty string as per the specs
    if (!(arr instanceof Array)) {
        return "";
    }
    // initialize the final string to an empty string
    var ret = "";
    // standard for loop for iterating through an array
    for (var i = 0; i < arr.length; i++) {
        // add the array element to the end of the return string
        // equivalent to ret = ret + arr[i]
        ret += arr[i];
        // if i is arr.length - 1, it's the last element of the array
        // so we don't want to add the separator
        if (i != arr.length - 1) {
            // but since it's not arr.length - 1 in this if statement
            // we can add the separator
            ret += sep;
        }
    }
    // we return the actual string
    return ret;
}

0
投票

在您的函数中,您正在使用连接数组方法。如果您确定arr总是只有两个元素,则可以简单地使用字符串连接字符+,如下所示:

arr[0] + arr[1]

为了使其更健壮,您可以遍历arr并将每个元素添加到结果输出中。

// Devine a variable to output
let output = '';
// Loop over the array elements
arr.forEach(el => {
  // Add eacht element to the existing output
  // The 'sep? sep + el: ' ' + el;' part checks if there is a seperator, if not add a space
  output += sep? sep + el: ' ' + el;
});

以上内容仅在output中已经添加了元素的情况下才有效,我们将需要添加第二项检查以查看输出是否仍为空字符串。

完整功能如下所示:

function join(arr, sep = '') {
  let output = '';
  arr.forEach(el => {
    if (output == '') {
      output += el;
    } else {
      output += sep? sep + el: ' ' + el;
    }
  });
  return output;
}

然后将是结果:

var myName = ["FirstName", "LastName"];
join(myName, ', ') // 'FirstName, LastName'

0
投票

简单地说? :

let myName = ["FirstName", "LastName"];

function join(arr, sep) {
  arr = arr || [] 
  sep = sep || ' '
  let res = ''
  for(let i=arr.length;i--;) res = (i?sep:'') + arr[i] + res
  return res 
};
console .log( '--no args ------>' + join() + '<---')
console .log( 'myName  -------->' + join(myName) + '<---')
console .log( 'myName  * ------>' + join(myName,'/')+ '<---')
console .log( "['a','b','c']--->" + join(['a','b','c'],' = ')+ '<---')
.as-console-wrapper { max-height: 100% !important }
© www.soinside.com 2019 - 2024. All rights reserved.