【JavaScript】01数组原型对象的最后一个元素、计数器

题目一:数组原型对象的最后一个元素

请你编写一段代码实现一个数组方法,使任何数组都可以调用 array.last() 方法,这个方法将返回数组最后一个元素。如果数组中没有元素,则返回 -1

你可以假设数组是 JSON.parse 的输出结果。

示例 1 :

复制代码
输入:nums = [null, {}, 3]
输出:3
解释:调用 nums.last() 后返回最后一个元素: 3。

示例 2 :

复制代码
输入:nums = []
输出:-1
解释:因为此数组没有元素,所以应该返回 -1。
提示:
  • arr 是一个有效的 JSON 数组

  • 0 <= arr.length <= 1000

    /**

    • @return {null|boolean|number|string|Array|Object}
      */
      Array.prototype.last = function() {

    };

    /**

    • const arr = [1, 2, 3];
    • arr.last(); // 3
      */

解题:

方法一:

复制代码
Array.prototype.last = function() {
    if(this.length===0){
        return -1;
    }else{
       return this[this.length-1] 
    }
    
};

方法二:

复制代码
Array.prototype.last = function() {
  return this.length === 0 ? -1 : this[this.length - 1];
}

作者:力扣官方题解
链接:https://leetcode.cn/problems/array-prototype-last/solutions/2506895/shu-zu-yuan-xing-dui-xiang-de-zui-hou-yi-4phe/
来源:力扣(LeetCode)

题目二:计数器

给定一个整型参数 n,请你编写并返回一个 counter函数。这个 counter函数最初返回 n,每次调用它时会返回前一个值加 1 的值 ( n , n + 1 , n + 2 ,等等)。

示例 1:

复制代码
输入:
n = 10 
["call","call","call"]
输出:[10,11,12]
解释:
counter() = 10 // 第一次调用 counter(),返回 n。
counter() = 11 // 返回上次调用的值加 1。
counter() = 12 // 返回上次调用的值加 1。

示例 2:

复制代码
输入:
n = -2
["call","call","call","call","call"]
输出:[-2,-1,0,1,2]
解释:counter() 最初返回 -2。然后在每个后续调用后增加 1。

提示:

  • -1000 <= n <= 1000
  • 0 <= calls.length <= 1000
  • calls[i] === "call"

解题:

方法一:

复制代码
function createCounter(n) {  
    let count = n; // 初始化计数值为 n  
    return function() {  
        return count++; // 返回当前计数值,并同时将其递增  
    };  
} 

方法二:

复制代码
var createCounter = function(n) {
  return function() {
    return n++;      
  };
};

作者:力扣官方题解
链接:https://leetcode.cn/problems/counter/solutions/2487678/ji-shu-qi-by-leetcode-solution-xuwj/
来源:力扣(LeetCode)
相关推荐
江畔柳前堤6 小时前
大语言模型分布式训练:从并行策略到万卡工程的系统梳理
人工智能·分布式·深度学习·算法·目标检测·机器学习·语言模型
Doraemomo6 小时前
数据结构-环形链表
java·数据结构·链表
Forever Nore7 小时前
LeetCode 4 寻找两个正序数组的中位数 - 二分
算法·leetcode
罗西的思考9 小时前
【OpenClaw具身硬件】MiniClaw 阅读笔记---(1)基础
人工智能·算法·机器学习
蛋先生DX9 小时前
大模型参数存储格式揭秘:BF不是男朋友
深度学习·算法·llm
爱跳舞的烤冷面10 小时前
自学嵌入式第22天(数据结构——哈希)
数据结构·算法·哈希算法
猎嘤一号10 小时前
博弈论(Game Theory)的理论、算法与工程
人工智能·算法·安全·博弈论
月光船幽幽10 小时前
影子模式下保护 logits 不被修改
人工智能·python·算法
马拉AI10 小时前
腾讯开源 Agent 记忆系统,AI“换对话就忘”的问题有了新解法(附安装使用教程)
人工智能·算法·开源·科研
MC皮蛋侠客12 小时前
Redis 系列(一):全景与最小闭环——从 `SET` 命令到内存数据结构
数据结构·数据库·redis