【发布时间】:2018-11-02 02:29:51
【问题描述】:
这个 addtoTaskList 函数需要将接收到的任务分成 2 个数组(?)或用逗号分隔的两个任务,然后将它们连接起来并添加到任务数组中。按照目前的代码,它将拆分值输出到任务列表,但也输出一个非拆分副本,并在每个条目后清除任务列表,如下所示:
我主要需要连接方面的帮助,谢谢!
"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();
};
【问题讨论】:
-
虽然没有必要,但我建议您使用 JSON.stringify(tasks) 和 JSON.parse(storage) 而不是使用“|”加入和拆分数组人物。这样,如果有人输入“|”添加任务时,它不会向您的任务数组添加额外的值。
-
谢谢!!!很抱歉浪费你的时间:(你是我的英雄
标签: javascript arrays split concatenation