简体   繁体   English

在不使用 split() 或任何内置方法且不超过 1 个参数的情况下,在 Javascript 中将字符串转换为数组?

[英]Convert a String to an Array in Javascript without using split() or any built-in methods and with no more than 1 parameter?

Convert a String to an Array in Javascript without using split() or any built-in methods?在 Javascript 中将字符串转换为数组而不使用 split() 或任何内置方法?

input:输入:

str = "Iam a fullstack javascript developer"

output:输出:

arr = [ 'Iam', 'a', 'fullstack', 'javascript', 'developer' ]

confirmation:确认:

console.log(arr[0]) // Iam

 var str="Iam a fullstack javascript developer"; var strCharArr; [...strCharArr]=str; var arr=strCharArr.reduce((acc, cv)=>{if(cv==" ") acc.push(""); else acc[acc.length-1]+=cv; return acc;},[""]); console.log(arr);

[...strCharArr]=str splits the string into an array of characters. [...strCharArr]=str将字符串拆分为字符数组。
reduce starts with an array of one element of empty string ( [""] ), reduce以一个包含一个空字符串元素的数组( [""] )开始,
and either adds characters, or, in case of a space, adds an empty string element.并且要么添加字符,要么在空格的情况下添加一个空字符串元素。

Here is the solution这是解决方案

function stringToArray(str) {
    let arr = [''];
    let j = 0;

    for (let i = 0; i < str.length; i++) {
        if (str.charAt(i) == " ") {
            j++;
            arr.push('');
        } else {
            arr[j] += str.charAt(i);
        }
    }
    return arr;
}

const arr = stringToArray("Iam a fullstack javascript developer")
console.log(arr[0]) // Iam

Recursive approach with using indexOf and slice使用indexOfslice递归方法

 str = "Iam a fullstack javascript developer"; const split = (str, arr) => { const index = str.indexOf(" "); if (index > -1) { arr.push(str.slice(0, index)); split(str.slice(index + 1), arr); } else { arr.push(str); } return ""; }; const chunks = (str) => { const arr = []; split(str, arr); return arr; }; console.log(chunks(str));

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

相关问题 如何在不使用内置Array方法的情况下删除javascript中的数组元素? - How to delete an array element in javascript without using any of built-in Array methods? 没有任何内置功能的分割字符串 - Split string without any built-in functions 在javascript中按降序对数组进行排序,而无需使用任何内置方法 - sorting an array in descending order in javascript without using any built-in method 没有内置 JavaScript 方法的单词大写 - Capitalize words without built-in JavaScript methods 在JavaScript中将数组作为内置函数参数传递 - Passing an array as a built-in function parameter in JavaScript JavaScript 中是否有未定义数据类型的内置方法? - Are there any built-in methods for undefined data type in JavaScript? 如何在不使用Java库和内置方法的情况下计算平方根? - How to calculate the square root without using library and built-in methods in Javascript? 递归查找 Javascript 中的字符串长度(无内置方法) - Find length of string in Javascript (no built-in methods) recursively 有关不同内置数组方法的术语Javascript - Terminology regarding different built-in array methods Javascript 在不使用任何内置函数的情况下修剪字符串左侧的空白 - Trimming white space on left side of string without using any built-in functions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM