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. 手把手教你实现折线图之------安卓最好用的图表库hellocharts之最详细的使用介绍

    因为项目需要搞一个折线图,按照日期显示相应的成绩,所以有了本文. 以前用过一次XCL-chart,但是感觉只适合固定图表,不去滑动的那种,因为你一滑动太卡了你懂得(毕竟作者好久没更新优化了),拙言大神 ...

  2. 【python】 urllib.unquote()

    来源:http://blog.csdn.net/anhuidelinger/article/details/10096727 urllib.unquote() 字符串被当作url提交时会被自动进行ur ...

  3. [Ubuntu] ubuntu10.04系统维护之Wine的安装

    在介绍安装wine之前,我想是有必要先介绍一下Wine的.当然,如果是Liunx的高手,我想是没必要看的,但是对于笔者这样的菜鸟级人物还是需要看一下的. Wine是一款Liunx下的模拟器软件,但是W ...

  4. August 11th 2016, Week 33rd Thursday

    A particular fine spring came around. 转眼又是一番分外明媚的春光. Hey, it is hot outside, sometimes even unbearab ...

  5. C# 类中索引器的使用二

    索引器(Indexer)是C#引入的一个新型的类成员,它使得类中的对象可以像数组那样方便.直观的被引用.索引器非常类似于属性,但索引器可以有参数列表,且只能作用在实例对象上,而不能在类上直接作用.定义 ...

  6. python基础——单元测试

    python基础——单元测试 如果你听说过“测试驱动开发”(TDD:Test-Driven Development),单元测试就不陌生. 单元测试是用来对一个模块.一个函数或者一个类来进行正确性检验的 ...

  7. MysqlDumpslow

    可以帮助分析慢查询. 选项: -n 10 列出最近10条慢查询 如: mysqldumpslow

  8. CROSS JOIN连接用于生成两张表的笛卡尔集

    将两张表的情况全部列举出来 结果表: 列= 原表列数相加 行= 原表行数相乘     CROSS JOIN连接用于生成两张表的笛卡尔集. 在sql中cross join的使用: 1.返回的记录数为两个 ...

  9. JavaScript基础——处理字符串

    String对象是迄今为止在JavaScript中最常用的对象.在你定义一个字符串数据类型的变量的任何时候,JavaScript就自定为你创建一个String对象.例如: var myStr = &q ...

  10. const和#define 区别

    1: 编译器处理不同     define宏是在预处理阶段展开,const常量是编译运行阶段使用. 2:类型和安全检查不同 const常量有数据类型,而宏常量没有数据类型,仅仅是展开.编译器可以对前者 ...