gpt4 book ai didi

javascript - 如何拆分字符串对象然后连接并添加到数组

转载 作者:行者123 更新时间:2023-12-03 00:49:31 26 4
gpt4 key购买 nike

这个addtoTaskList函数需要将接收到的任务分成2个数组(?)或用逗号分隔的两个任务,然后将它们连接起来并添加到任务数组中。正如当前代码所示,它将分割值输出到任务列表,但也输出非分割重复值,并在每次输入后清除任务列表,如下所示: Duplicate Output

我想,我主要需要连接方面的帮助,谢谢!

"use strict";
var $ = function(id) { return document.getElementById(id); };

var tasks = [];

var displayTaskList = function() {
var list = "";
// if there are no tasks in tasks array, check storage
if (tasks.length === 0) {
// get tasks from storage or empty string if nothing in storage
var storage = localStorage.getItem("tasks") || "";

// if not empty, convert to array and store in global tasks variable
if (storage.length > 0) { tasks = storage.split("|"); }
}

// if there are tasks in array, sort and create tasks string
if (tasks.length > 0) {
// tasks.sort();
list = tasks.join("\n");
}
// display tasks string and set focus on task text box
$("task_list").value = list;
$("task").focus();
};

var addToTaskList = function() {
var task = $("task");
if (task.value === "") {
alert("Please enter a task.");
} else {

// add task to array and local storage
var partsOfStr = task.value.split(',');
tasks = partsOfStr.concat(task.value);

localStorage.tasks = tasks.join("|");

// clear task text box and re-display tasks
task.value = "";
displayTaskList();
}
};

var clearTaskList = function() {
tasks.length = 0;
localStorage.tasks = "";
$("task_list").value = "";
$("task").focus();
};

window.onload = function() {
$("add_task").onclick = addToTaskList;
$("clear_tasks").onclick = clearTaskList;
displayTaskList();
};

最佳答案

您正在尝试将数组 (partsOfStr) 与字符串 (task.value) 连接起来。也许您打算使用 tasks 而不是 task.value

tasks = partsOfStr.concat(task.value);

应该是:

tasks = tasks.concat(partsOfStr);

关于javascript - 如何拆分字符串对象然后连接并添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53111936/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com