Utilities

type

// is this a function?
typeof someValue === 'function'; // is this an object?
someValue != null &&
Object.prototype.toString.call(someValue) === "[object Object]"; // works in modern browsers
Array.isArray(someValue); // works in all browsers
Object.prototype.toString.call(someValue) === "[object Array]";

Combine and copy objects

// our helper function
function extend(first, second) {
for (var secondProp in second) {
var secondVal = second[secondProp];
// Is this value an object? If so, iterate over its properties, copying them over
if (secondVal && Object.prototype.toString.call(secondVal) === "[object Object]") {
first[secondProp] = first[secondProp] || {};
extend(first[secondProp], secondVal);
}
else {
first[secondProp] = secondVal;
}
}
return first;
}; // example use - updates o1 with the content of o2
extend(o1, o2); // example use - creates a new object that is the aggregate of o1 & o2
var newObj = extend(extend({}, o1), o2);

Iterate over object properties

for (var myObjectProp in myObject) {
// deal with each property in the `myObject` object...
} // works in all browsers
for (var prop in myObject) {
if (myObject.hasOwnProperty(prop)) {
// deal w/ each property that belongs only to `myObject`...
}
} // works in modern browsers
Object.keys(myObject).forEach(function(prop) {
// deal with each property that belongs to `myObject`...
});

Iterate over array elements

// works in all browsers
for (var index = 0; i < myArray.length; i++) {
var arrayVal = myrray[index];
// handle each array item...
} // works in modern browsers
myArray.forEach(function(arrayVal, arrayIndex) {
// handle each array item
}

Find an element in an array

// works in modern browsers
var indexOfValue = theArray.indexOf('c'); // works in all browsers
function indexOf(array, valToFind) {
var foundIndex = -1;
for (var index = 0; index < array.length; i++) {
if (theArray[index] === valToFind) {
foundIndex = index;
break;
}
}
} // example use
indexOf(theArray, 'c'); // works in modern browsers
var allElementsThatMatch = theArray.filter(function(theArrayValue) {
return theArrayValue !== 'b';
}); // works in all browsers
function filter(array, conditionFunction) {
var validValues = [];
for (var index = 0; index < array.length; i++) {
if (conditionFunction(theArray[index])) {
validValues.push(theArray[index]);
}
}
} // use example
var allElementsThatMatch = filter(theArray, function(arrayVal) {
return arrayVal !== 'b';
})

Turn a pseudo-array into a real array

var realArray = [].slice.call(pseudoArray);

[].forEach.call(pseudoArray, function(arrayValue) {
// handle each element in the pseudo-array...
});

Modify a function

Change a function's context

// works in modern browsers
function Outer() {
var eventHandler = function(event) {
this.foo = 'buzz';
}.bind(this); this.foo = 'bar';
// attach `eventHandler`...
} var outer = new Outer();
// event is fired, triggering `eventHandler` // works in all browsers
function Outer() {
var self = this,
eventHandler = function(event) {
self.foo = 'buzz';
}; this.foo = 'bar';
// attach `eventHandler`...
} var outer = new Outer();
// event is fired, triggering `eventHandler`

Create a new function with some pre-determined arguments

function log(appId, level, message) {
// send message to central server
} var ourLog = log.bind(null, 'master-shake'); // example use
ourLog('error', 'dancing is forbidden!');

Trim a string

// works in modern browsers
' hi there! '.trim(); // works in all browsers, but needed in IE 8 and older
' hi there! '.replace(/^\s+|\s+$/g, ''); // works in all browsers
function trim(string) {
if (string.trim) {
return string.trim();
}
return string.replace(/^\s+|\s+$/g, '');
}

Associate data with an HTML element

// works in all browsers
var data = (function() {
var lastId = 0,
store = {}; return {
set: function(element, info) {
var id;
if (element.myCustomDataTag === undefined) {
id = lastId++;
element.myCustomDataTag = id;
}
store[id] = info;
}, get: function(element) {
return store[element.myCustomDataTag];
}
};
}());
// use it

// make the elements aware of each other
var one = document.getElementById('one'),
two = document.getElementById('two'),
toggle = function(element) {
if (element.style.display !== 'none') {
element.style.display = 'none';
}
else {
element.style.display = 'block';
}
}; data.set(one, {partnerElement: two});
data.set(two, {partnerElement: one}); // on click, either hide or show the partner element
// remember to use `attachEvent` in IE 8 and older, if support is required
one.addEventListener('click', function() {
toggle(data.get(one).partnerElement);
});
two.addEventListener('click', function() {
toggle(data.get(two).partnerElement);
});
// works only in the latest browsers
// make the elements aware of each other
var weakMap = new WeakMap(),
one = document.getElementById('one'),
two = document.getElementById('two'),
toggle = function(element) {
if (element.style.display !== 'none') {
element.style.display = 'none';
}
else {
element.style.display = 'block';
}
}; weakMap.set(one, {partnerElement: two});
weakMap.set(two, {partnerElement: one});
// on click, either hide or show the partner element
// remember to use `attachEvent` in IE 8 and older, if support is required
one.addEventListener('click', function() {
toggle(weakMap.get(one).partnerElement);
});
two.addEventListener('click', function() {
toggle(weakMap.get(two).partnerElement);
});
// works in all browsers
var data = window.WeakMap ? new WeakMap() : (function() {
var lastId = 0,
store = {}; return {
set: function(element, info) {
var id;
if (element.myCustomDataTag === undefined) {
id = lastId++;
element.myCustomDataTag = id;
}
store[id] = info;
}, get: function(element) {
return store[element.myCustomDataTag];
}
};
}());

no-jquery 05 Utilities的更多相关文章

  1. jQuery来源学习笔记:扩展的实用功能

    // 扩展的实用功能 jQuery.extend({ // http://www.w3school.com.cn/jquery/core_noconflict.asp // 释放$的 jQuery 控 ...

  2. jQuery源码分析-03扩展工具函数jQuery.extend

    // 扩展工具函数 jQuery.extend({ // http://www.w3school.com.cn/jquery/core_noconflict.asp // 释放$的 jQuery 控制 ...

  3. 改善你的jQuery的25个步骤 千倍级效率提升

    1. 从Google Code加载jQueryGoogle Code上已经托管了多种JavaScript类库,从Google Code上加载jQuery比直接从你的服务器加载更有优势.它节省了你服务器 ...

  4. jQuery选择器引擎和Sizzle介绍

    一.前言 Sizzle原来是jQuery里面的选择器引擎,后来逐渐独立出来,成为一个独立的模块,可以自由地引入到其他类库中.我曾经将其作为YUI3里面的一个module,用起来畅通无阻,没有任何障碍. ...

  5. 从零开始学习jQuery (九) jQuery工具函数

    一.摘要 本系列文章将带您进入jQuery的精彩世界, 其中有很多作者具体的使用经验和解决方案,  即使你会使用jQuery也能在阅读中发现些许秘籍. 我们经常要使用脚本处理各种业务逻辑, 最常见的就 ...

  6. jquery遍历筛选数组的几种方法和遍历解析json对象

    jquery grep()筛选遍历数组 $().ready(    function(){        var array = [1,2,3,4,5,6,7,8,9];        var fil ...

  7. 改善你的jQuery的25个步骤

    1. 从Google Code加载jQueryGoogle Code上已经托管了多种JavaScript类库,从Google Code上加载jQuery比直接从你的服务器加载更有优势.它节省了你服务器 ...

  8. [转]JQuery - Sizzle选择器引擎原理分析

    原文: https://segmentfault.com/a/1190000003933990 ---------------------------------------------------- ...

  9. day63-webservice 09.jquery调用ajax

    WebService可以有很多种调用方式,除了之前说的,还可以有jquery.拿原生的Ajax做调用,拿jquery怎么调用啊?原生的能调,jquery指定也能调.原生的Ajax是通过网页直接点HTM ...

随机推荐

  1. ubuntu下安装mysql

    现在的软件越来越好安装,尤其是在ubuntu下安装软件,更是没有技巧,只需要在联网的情况下使用apt-get inatll 即可.在决定安装mysql之前,要先确定系统是否已经安装mysql.如下图: ...

  2. Android studio 自定义打包APK名称

    Android Studio打包应用默认生成的apk名称是:app-release.apk .如果我们要让生成的apk名跟我们版本包名有联系的话,那我们就要自定义生成的apk名了,要怎么做呢. 我们只 ...

  3. 【leetcode】Next Permutation(middle)

    Implement next permutation, which rearranges numbers into the lexicographically next greater permuta ...

  4. 基于SSH2的OA项目1.0_20161206_需求分析与框架搭建

    1. SSH项目 OA项目,办公自动化,将公司的数据,文档,流程实现在系统中的管理. 降低人员交流过程中的成本.提高办公的效率. 2 .系统管理 主要实现系统权限的管理,不同的用户登陆后看到菜单项不一 ...

  5. 最小集合(51nod 1616)

    A君有一个集合. 这个集合有个神奇的性质. 若X,Y属于该集合,那么X与Y的最大公因数也属于该集合. 但是他忘了这个集合中原先有哪些数字. 不过幸运的是,他记起了其中n个数字. 当然,或许会因为过度紧 ...

  6. MVC下HtmlHelper自带BeginForm表单提交与异步Ajax请求

    假如有一个数据表格UserInfo: public class UserInfo { public int Id { get; set; } public string Name { get; set ...

  7. logstash json和rubydebug 第次重启logstash都会把所有的日志读完 而不是只读入新输入的内容

    查看一下agent端的shipper的配置: # cat logstash_test2.shipper.conf input { file { path => ["/apps/logs ...

  8. 使用Autofac在ASP.NET Web API上实现依赖注入

    在ASP.NET Web API里使用Autofac 1.通过NuGet安装Autofac.WebApi(当时安装的是Autofac 3.1.0) PM > Install-Package Au ...

  9. 关于Python 获取windows信息收集

    收集一些Python操作windows的代码 (不管是自带的or第三方库)均来自网上 1.shutdown 操作 定时关机.重启.注销 #!/usr/bin/python #-*-coding:utf ...

  10. 【翻译十一】java-原子性操作

    Atomic Access In programming, an atomic action is one that effectively happens all at once. An atomi ...