如何编写接收参数并添加至数组的函数?含控制台输入代码排查
嘿,让我一步步帮你搞定这两个问题!
问题1:编写接收参数并添加至数组的函数
其实这个需求很容易实现,核心就是利用数组的push()方法把参数加入数组。这里给你一个基础的实现方式,你可以根据场景调整:
// 先初始化一个数组(如果需要复用的话,可以把数组和函数封装起来) let photoList = []; // 定义接收参数并添加到数组的函数 function addToPhotoList(photoName) { // 将传入的参数推入数组 photoList.push(photoName); // 返回更新后的数组,方便后续使用 return photoList; } // 测试下效果 console.log(addToPhotoList("sunflower")); // 输出: ["sunflower"] console.log(addToPhotoList("rose")); // 输出: ["sunflower", "rose"]
如果想要更封装的方式(比如每个实例独立数组),也可以用构造函数或者类,这个咱们在问题2里详细说~
问题2:修复控制台输入添加至数组的构造函数代码
先看你写的代码,有几个小细节出了问题,我帮你一一修正并解释:
你的原代码问题点:
- 访问实例的
listPhotos数组时,直接写listPhotos会被当成全局变量,必须用this.listPhotos指向当前实例的属性; push("x")里加了引号,会把字符串"x"硬塞进去,而不是传入的参数值,应该改成push(x);console.log(x.listPhotos)里的x是你传入的参数,不是实例本身,要打印更新后的数组得用this.listPhotos。
修正后的基础版本
function Album() { // 初始化实例的照片数组 this.listPhotos = ["bee", "ladybug", "caterpillar", "ant"]; // 定义添加照片的方法 this.addPhoto = function(photoName) { // 用this访问当前实例的数组,推入参数值 this.listPhotos.push(photoName); // 打印更新后的数组 console.log("更新后的相册:", this.listPhotos); // 返回更新后的数组 return this.listPhotos; } } // 测试使用 const myAlbum = new Album(); myAlbum.addPhoto("butterfly"); // 输出: 更新后的相册: ["bee", "ladybug", "caterpillar", "ant", "butterfly"]
加上控制台输入的版本
如果要接收用户在控制台的输入,分两种场景:
1. 浏览器环境(弹窗输入)
function Album() { this.listPhotos = ["bee", "ladybug", "caterpillar", "ant"]; this.addPhotoFromInput = function() { // 用prompt弹出输入框获取用户输入 const userInput = prompt("请输入要添加的照片名称:"); if (userInput) { // 判断用户是否输入了有效内容 this.listPhotos.push(userInput); console.log("更新后的相册:", this.listPhotos); return this.listPhotos; } } } const myAlbum = new Album(); myAlbum.addPhotoFromInput(); // 点击调用后会弹出输入框
2. Node.js终端环境(命令行输入)
需要用到Node.js内置的readline模块:
const readline = require('readline'); // 创建命令行输入输出接口 const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); function Album() { this.listPhotos = ["bee", "ladybug", "caterpillar", "ant"]; // 用箭头函数保证this指向当前Album实例 this.addPhotoFromInput = () => { rl.question("请输入要添加的照片名称:", (userInput) => { this.listPhotos.push(userInput); console.log("更新后的相册:", this.listPhotos); rl.close(); // 完成输入后关闭接口 }); } } const myAlbum = new Album(); myAlbum.addPhotoFromInput();
内容的提问来源于stack exchange,提问作者Efrex22
相关产品推荐
相关产品推荐

